package controllers

import (
	"net/http"
	"encoding/json"
	"git.oschina.net/YPTArch/auth/sys/logs"
	"git.oschina.net/YPTArch/auth/models"
	"git.oschina.net/YPTArch/auth/sys/config"
)


//redis 访问延时
func Validate(w http.ResponseWriter, r *http.Request)   {
	logs.Logger.Debug("success in validate")

	var result models.Result

	var token string
	urlToken, err := getRawQueryToken(r.URL.RawQuery)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:err.Error(), Data:""}
	}

	//url取到就不从header里取了
	if urlToken != "" {
		token = urlToken
	}else {
		headerToken, err := getHeaderToken(r)
		if err != nil {
			result = models.Result{Code:models.Unauthorized, Msg:err.Error(), Data:""}
		}

		if headerToken == "" {
			result = models.Result{Code:models.Unauthorized, Msg:"没有获取到token信息", Data:""}
		}else {
			token = headerToken
		}
	}

	reply, err := validateHandler(token)
	if err != nil {
		result = models.Result{Code:models.Unauthorized, Msg:"验证登录处理失败！", Data:""}
	}else {
		result = models.Result{Code:models.Ok, Msg:"验证登录成功！", Data:reply}
	}


	re, err := json.Marshal(result)
	if err != nil {
		logs.Logger.Error(err.Error())
		w.Write([]byte(models.ServerErr))
	}

	w.Write(re)
}

//验证处理
func validateHandler(tokenstring string) (reply  interface{}, err error)  {

	var uid string
	uid, err = parsingToken(tokenstring)
	if err != nil {
		return
	}

	reply, err = models.GetUserStruct(USER+uid)
	if err != nil {
		return
	}
	err = models.Delay(USER+uid, config.Conf.Expiration)
	return
}


